package com.clh.seckill.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author cailinhu
 * @Description TODO
 * @Date 2021-10-29 14:00
 * @Version 1.0
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //key的序列化操作
        template.setKeySerializer(new StringRedisSerializer());
        //value的序列号操作
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //hash类型key的序列化操作
        template.setHashKeySerializer(new StringRedisSerializer());
        //hash类型value序列化的操作
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(factory);
        return template;
    }

    @Bean
    public DefaultRedisScript<Boolean> script(){
        DefaultRedisScript<Boolean> script = new DefaultRedisScript<>();
        //加载脚本
        script.setLocation(new ClassPathResource("lock.lua"));
        //设置返回结果
        script.setResultType(Boolean.class);
        return script;
    }
    @Bean("stockluaScript")
    public DefaultRedisScript<Long> stockluaScript(){
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        //加载脚本
        script.setLocation(new ClassPathResource("stock.lua"));
        //设置返回结果
        script.setResultType(Long.class);
        return script;
    }

}
